package com.zmn.plat.business.impl.part;

import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.plat.business.interfaces.part.PartSkuBService;
import com.zmn.plat.model.entity.part.PartCategory;
import com.zmn.plat.model.entity.part.PartSku;
import com.zmn.plat.model.entity.part.PartSkuPrice;
import com.zmn.plat.model.entity.part.PartSkuQuery;
import com.zmn.plat.model.vo.part.PartSkuVO;
import com.zmn.plat.services.interfaces.part.PartCategoryService;
import com.zmn.plat.services.interfaces.part.PartSkuPriceService;
import com.zmn.plat.services.interfaces.part.PartSkuService;

/**
 * 类描述： PartSkuBServiceImpl
 *
 * @author DaiZhichao
 * @since 2018/10/22 14:30
 */

@Service
public class PartSkuBServiceImpl implements PartSkuBService {
    @Resource
    PartSkuService partSkuService;
    @Resource
    PartCategoryService partCategoryService;
    @Resource
    PartSkuPriceService partSkuPriceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertSkuAndPrice(PartSku partSku, PartSkuPrice skuPrice, LoginStaff mcStaff) {
        partSkuService.insert(partSku, mcStaff);
        skuPrice.setSkuId(partSku.getSkuId());
        partSkuPriceService.insert(skuPrice, mcStaff);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSkuAndPrice(PartSku partSku, PartSkuPrice skuPrice, LoginStaff mcStaff) {

        partSkuService.updateByKey(partSku, mcStaff);
        partSkuPriceService.updateByKey(skuPrice, mcStaff);
    }

    @Override
    public Boolean findIdenticalPart(PartSkuVO partSkuVO) {
        PartSkuQuery query = new PartSkuQuery();
        query.setCategId(partSkuVO.getCategId());
        List<PartSku> skuListByCateId = partSkuService.listByQuery(query);

        return skuListByCateId.stream().filter(partSku -> !Objects.equals(partSku.getSkuId(), partSkuVO.getSkuId())).anyMatch(partSku -> Objects.equals(partSku.getName(), partSkuVO.getName()));
    }

    /**
     * 描述: 遍历配件分类递归获取所有配件（未测试）
     *
     * @param voList
     *            传入的 配件VO 列表
     * @param categId
     *            配件分类ID
     * @since 2019/03/08 15:55
     */
    @Override
    public List<PartSkuVO> getAllPart(List<PartSkuVO> voList, Integer categId) {
        PartCategory byKey = partCategoryService.findByKey(categId);
        PartSkuQuery query = new PartSkuQuery();
        query.setCategId(categId);
        voList.addAll(partSkuService.listVOPageByQuery(query));

        if (byKey.getParentId() > 1) {
            List<PartCategory> categoryList = partCategoryService.listByParentId(categId, null);
            for (PartCategory category : categoryList) {
                this.getAllPart(voList, category.getCategId());
            }
        }
        return voList;
    }

}
